#include "Window.h"

Window* Window::instance = NULL;

Window::Window(int resX, int resY, const char* windowTitle, int globalScale) {
	if(SDL_Init(SDL_INIT_VIDEO) < 0) {  //  | SDL_INIT_AUDIO
		printf("Error initialising SDL.\n");
		return;
	}

	SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

	surface = SDL_SetVideoMode(
        resX*globalScale,
        resY*globalScale,
        16,
		SDL_DOUBLEBUF | SDL_HWSURFACE | SDL_ANYFORMAT | SDL_OPENGL
    );

	if(surface == NULL) {
		printf("Error creating SDL surface.\n");
		return;
	}

	//SDL_ShowCursor(SDL_DISABLE);

	// Create OpenGL viewport
	glViewport(0,0,resX*globalScale,resY*globalScale);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

    // Create orthographic viewing plane
	glOrtho(0.0f, (GLfloat) (resX*globalScale), (GLfloat) resY*globalScale ,0.0f,-1.0f,1.0f);
	glScalef((GLfloat) globalScale, (GLfloat) globalScale, 1.0f);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glScissor(0, 0, resX*globalScale, resY*globalScale);
	glEnable(GL_SCISSOR_TEST);
	glEnable(GL_TEXTURE_2D);
	glDisable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);

	this->resX = resX;
	this->resY = resY;

    if(windowTitle != NULL) setTitle(windowTitle);

	instance = this;
	running = true;
}

Window::~Window()
{
}

void Window::setBackgroundColour(Uint8 r, Uint8 g, Uint8 b)
{
    glClearColor((float)r / 255.0f, (float)g / 255.0f, (float)b / 255.0f, 1.0f);
}

void Window::process()
{
	doEvents();
	doFrame();
}

void Window::doEvents()
{
	SDL_Event event;
	while (SDL_PollEvent(&event)){
	    if(event.type == SDL_QUIT) running = false;
	}

	// Poll the keyboard for updates
	Keyboard::update();
}

void Window::doFrame()
{
	glLoadIdentity();

	SDL_GL_SwapBuffers();
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
}

Window* Window::getInstance()
{
    return instance;
}
